<?php

namespace mongrove;

use \Exception;

/**
 * The EnumField allows a set of preset values to be set as value.
 *
 * @author Gido Hakvoort <gido@hakvoort.it>
 * @author Michiel Hakvoort <michiel@hakvoort.it>
 *
 */
class EnumField extends SimpleField {

    protected $enums;

    /**
     *
     * Define a new EnumField with the given options and possible default option
     *
     * @param array $enums The allowed values
     * @param mixed $default The default value
     */
    public function __construct(array $enums = array(), $default = null) {
        parent :: __construct();

        $this->enums = $enums;

        if($default !== null) {
            $this->setValue($default);
        }
    }

    /**
     * (non-PHPdoc)
     * @see src/mongrove.SimpleField::setValueImpl()
     */
    protected function setValueImpl($value) {
        if($this->value === $value) {
            return false;
        }

        if(!in_array($value, $this->enums)) {
            throw new Exception("'$value' is not a valid value for this field");
        }

        $this->value = $value;

        return true;
    }
}